package com.graduation.mybatis.controller;

import com.graduation.mybatis.bean.DietRecord;
import com.graduation.mybatis.bean.DietRecordVO;
import com.graduation.mybatis.bean.NutritionSummary;
import com.graduation.mybatis.service.DietPlansService;
import com.graduation.mybatis.service.DietRecordService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * (DietRecord)表控制层
 *
 * @author makejava
 * @since 2025-03-29 21:10:37
 */
@RestController
@RequestMapping("dietRecord")
public class DietRecordController {
    /**
     * 服务对象
     */
    @Autowired
    private DietRecordService dietRecordService;

    @Resource
    private DietPlansService dietPlansService;
    /**
     * 分页查询
     */
//    @GetMapping("/page")
//    public ResponseEntity<Page<DietRecord>> queryByPage(DietRecord dietRecord, PageRequest pageRequest) {
//        Page<DietRecord> page = new Page<>(pageRequest.getPageNum(), pageRequest.getPageSize());
//        QueryWrapper<DietRecord> wrapper = new QueryWrapper<>(dietRecord);
//        return ResponseEntity.ok(dietRecordService.page(page, wrapper));
//    }
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<DietRecord> queryById(@PathVariable Integer id) {
        return ResponseEntity.ok(this.dietRecordService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param dietRecord 实体
     * @return 新增结果
     */
    @PostMapping
    public ResponseEntity<DietRecord> add(@RequestBody DietRecord dietRecord) {
        return dietRecordService.save(dietRecord) ?
                ResponseEntity.ok(dietRecord) :
                ResponseEntity.internalServerError().build();
    }

    /**
     * 编辑数据
     *
     * @param dietRecord 实体
     * @return 编辑结果
     */
    @PutMapping
    public ResponseEntity<DietRecord> edit(DietRecord dietRecord) {
        return dietRecordService.updateById(dietRecord) ?
                ResponseEntity.ok(dietRecord) :
                ResponseEntity.internalServerError().build();
    }

    /**
     * 删除数据
     *
     * @param id 主键
     * @return 删除是否成功
     */
    @DeleteMapping
    public ResponseEntity<Boolean> deleteById(@PathVariable Integer id) {
        return ResponseEntity.ok(this.dietRecordService.removeById(id));
    }

    /**
     * 根据foodEntryId删除
     * @param foodEntryId
     * @return
     */
    @DeleteMapping("/foodEntry/{foodEntryId}")
    public ResponseEntity<Map<String, Object>> deleteRecordAndFoodEntry(@PathVariable Long foodEntryId) {
        Map<String, Object> response = new HashMap<>();
        if (!dietRecordService.removeByrecordIdAndFoodEntryId(foodEntryId)) {
            response.put("success", false);
            response.put("message", "食物删除失败");
        } else {
            response.put("success", true);
            response.put("message", "食物删除成功");
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 根据用户ID和餐次获取饮食记录
     *
     * @param userId     用户ID
     * @param mealType   餐次（1-早餐，2-午餐，3-晚餐）
     * @return 饮食记录列表
     */
    @GetMapping("/{userId}/meals/{mealType}")
    public ResponseEntity<Map<String, Object>> getDietRecordsByUserIdAndMealType(
            @PathVariable Long userId,
            @PathVariable Integer mealType,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        // 默认使用当天日期
        if (date == null) {
            date = LocalDate.now();
        }

        List<DietRecordVO> records = dietRecordService.getDailyRecords(userId, mealType, date);

        // 计算营养总和
        NutritionSummary summary = dietRecordService.calculateNutritionSummary(records);

        Map<String, Object> response = new HashMap<>();
        if(records.size() <=0) {
            response.put("success",false);
            response.put("message","没有查询到数据");

        }else{
            response.put("success",true);
            response.put("records", records);
            response.put("summary", summary);
            response.put("message","已查询到数据");
        }

        return ResponseEntity.ok(response);
    }

    /**
     * 根据用户ID获取所有饮食记录
     *
     * @param userId 用户ID
     * @return 饮食记录列表
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getAllDietRecordsByUserId(@PathVariable Long userId,@RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        // 默认使用当天日期
        if (date == null) {
            date = LocalDate.now();
        }

        List<DietRecordVO> result = dietRecordService.getRecordsByUserId(userId,date);
        Map<String, Object> response = new HashMap<>();
        response.put("data", Map.of(
                "success", true,
                "message", "获取成功",
                "data", result
        ));
        return ResponseEntity.ok(response);
    }

    /**
     * 根据用户ID获取每日营养总合
     *
     * @param userId 用户ID
     * @param date   日期
     * @return 包含总合和餐次 summaries
     */
    @GetMapping("/nutrition/summary/{userId}")
    public ResponseEntity<Map<String, Object>> getDailyNutritionSummary(
            @PathVariable Long userId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {

        if (date == null) date = LocalDate.now();

        // 1. 获取所有餐次数据
        Map<Integer, NutritionSummary> mealSummaries = dietRecordService.getDailyMealSummaries(userId, date);

        // 计算总合时跳过null值
        NutritionSummary totalSummary = new NutritionSummary();
        mealSummaries.values().stream()
                .filter(Objects::nonNull)
                .forEach(totalSummary::merge);

        // 获取餐次食物数据
        List<DietRecordVO> dietRecords = dietPlansService.getDietRecordsByUserId(Math.toIntExact(userId));

        // 计算每日推荐值（计划中所有食物的营养总值）
        double dailyCaloriesGoal = dietRecords.stream().mapToDouble(DietRecordVO::getCalories).sum();
        double dailyProteinGoal = dietRecords.stream().mapToDouble(DietRecordVO::getProtein).sum();
        double dailyFatGoal = dietRecords.stream().mapToDouble(DietRecordVO::getFat).sum();
        double dailyCarbohydrateGoal = dietRecords.stream().mapToDouble(DietRecordVO::getCarbohydrate).sum();

        Map<String, Object> response = new HashMap<>();
        response.put("data", Map.of(
                "total", totalSummary,
                "goals", Map.of(
                        "caloriesGoal", dailyCaloriesGoal,
                        "proteinGoal", dailyProteinGoal,
                        "fatGoal", dailyFatGoal,
                        "carbohydrateGoal", dailyCarbohydrateGoal),
                "success",true
        ));

        return ResponseEntity.ok(response);
    }

    /**
     * 根据用户ID获取每日营养总合
     *
     * @param userId 用户ID
     * @param period   日期
     * @return 包含总合和餐次 summaries
     */
    @GetMapping("/nutritionPeriod/summary/{userId}")
    public ResponseEntity<Map<String, Object>> getPeriodNutritionSummary(
            @PathVariable Long userId,
            @RequestParam(required = false,defaultValue = "1") Integer period,
            @RequestParam(required = false) String date) {


        // 如果 date 为空，默认使用当前日期
        if (date == null || date.isEmpty()) {
            date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }

        // 1. 获取所有餐次数据
        Map<Integer, NutritionSummary> mealSummaries = dietRecordService.getPeriodyMealSummaries(userId, period, date);

        // 计算总合时跳过null值
        NutritionSummary totalSummary = new NutritionSummary();
        mealSummaries.values().stream()
                .filter(Objects::nonNull)
                .forEach(totalSummary::merge);

        Map<String, Object> response = new HashMap<>();
        response.put("data", Map.of(
                "total", totalSummary,
                "mealSummaries", mealSummaries,
                "success",true
        ));

        return ResponseEntity.ok(response);
    }


}

